package com.ruoyi.common.utils.file

import com.ruoyi.common.constant.*
import com.ruoyi.framework.config.RuoYiConfig
import org.apache.commons.lang3.StringUtils
import org.apache.poi.util.IOUtils
import org.slf4j.LoggerFactory
import java.io.*
import java.net.URL
import java.util.*

/**
 * 图片处理工具类
 *
 * @author ruoyi
 */
object ImageUtils {
    private val log = LoggerFactory.getLogger(ImageUtils::class.java)
    fun getImage(imagePath: String): ByteArray? {
        val `is` = getFile(imagePath)
        return try {
            IOUtils.toByteArray(`is`)
        } catch (e: Exception) {
            log.error("图片加载异常 {}", e)
            null
        } finally {
            IOUtils.closeQuietly(`is`)
        }
    }

    fun getFile(imagePath: String): InputStream? {
        try {
            var result = readFile(imagePath)
            result = (result!!).copyOf(result.size)
            return ByteArrayInputStream(result)
        } catch (e: Exception) {
            log.error("获取图片异常 {}", e)
        }
        return null
    }

    /**
     * 读取文件为字节数据
     *
     * @param url 地址
     * @return 字节数据
     */
    fun readFile(url: String): ByteArray? {
        var inputStream: InputStream? = null
        return try {
            if (url.startsWith("http")) {
                // 网络地址
                val urlObj = URL(url)
                val urlConnection = urlObj.openConnection()
                urlConnection.connectTimeout = 30 * 1000
                urlConnection.readTimeout = 60 * 1000
                urlConnection.doInput = true
                inputStream = urlConnection.getInputStream()
            } else {
                // 本机地址
                val localPath: String = RuoYiConfig.getProfile()!!
                val downloadPath = localPath + StringUtils.substringAfter(url, Constants.RESOURCE_PREFIX)
                inputStream = FileInputStream(downloadPath)
            }
            IOUtils.toByteArray(inputStream)
        } catch (e: Exception) {
            log.error("获取文件路径异常 {}", e)
            null
        } finally {
            IOUtils.closeQuietly(inputStream)
        }
    }
}
